package com.sghd.fight.net;

import com.sghd.common.event.Event;
import com.sghd.common.event.EventBus;
import com.sghd.common.socket.core.Message;
import com.sghd.common.socket.session.Session;
import com.sghd.common.socket.session.SessionClose;
import com.sghd.common.socket.session.SessionOpen;
import com.sghd.fight.module.game.event.DisconnectEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author frank
 * @date 2018-10-31 16:56
 * @desc
 **/
@Component
public class SessionEvent implements SessionClose, SessionOpen {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private EventBus eventBus;

    @Override
    public void sessionClosed(Session session, int cause) {
        long playerId = 0;
        Object identity = session.getIdentity();
        if (identity != null) {
            playerId = (Long) identity;
        }
        switch (cause) {
            case Session.TIMEOUT:
                logger.debug("玩家[{}]连接超时！", session.getIdentity());
                session.write(Message.Empty(-101));
            default:
                Event<DisconnectEvent> disconnectEvent = DisconnectEvent.valueOf(playerId, cause, session);
                eventBus.syncPost(disconnectEvent);
                break;
        }
    }

    @Override
    public void sessionOpened(Session session) {
    }
}
